﻿using Dapper;
using Newtonsoft.Json;
using PersonalWebsite.Core.CQRS;
using PersonalWebsite.Core.Result;

namespace PersonalWebsite.Application.Queries.Post
{
    public class GetPostVO
    {
        public int Id { get; init; }
        public string Title { get; init; }
        public string Category { get; init; }
        public string Desc { get; init; }
        public string[] Tags
        {
            get
            {
                if (string.IsNullOrEmpty(TagStr))
                {
                    return [];
                }

                return JsonConvert.DeserializeObject<string[]>(TagStr);
            }
        }
        public string TagStr { get; set; }
        public string Time { get { return PublishTime.ToString("yyyy/MM/dd"); } }
        public bool IsOutlink { get; init; }
        public string LinkUrl { get; init; }

        public DateTime PublishTime { get; init; }
    }

    public class GetPostQuery : IQuery<ApiResult<List<GetPostVO>>, List<GetPostVO>>
    {
        public string Category { get; init; }
    }

    public class GetPostQueryHandler : QueryHandler<GetPostQuery, ApiResult<List<GetPostVO>>, List<GetPostVO>>
    {
        private readonly IDBConnectionFactory dBConnectionFactory;

        public GetPostQueryHandler(IDBConnectionFactory dBConnectionFactory) : base(dBConnectionFactory)
        {
            this.dBConnectionFactory = dBConnectionFactory;
        }

        public override async Task<ApiResult<List<GetPostVO>>> Handle(GetPostQuery request, CancellationToken cancellationToken)
        {
            string whereCategory = !string.IsNullOrEmpty(request.Category) ?
                $" WHERE Category='{request.Category}' " : request.Category;

            using var dbConnection = dBConnectionFactory.GetDbConnection();

            string sql = @$"SELECT
                    	Id,
                    	Title,
                    	Category,
                    	`Desc`,
                    	Tags AS TagStr,
                    	Time As PublishTime,
                    	IsOutLink,
                    	LinkUrl 
                        FROM
                    	WP_Post {whereCategory} order by PublishTime";

            var result = await dbConnection.QueryAsync<GetPostVO>(sql);

            return await Task.FromResult(ApiResult<List<GetPostVO>>.Success(result?.ToList()));
        }
    }
}
